<?php
/**
 * @author Pramod thakur <pramod19kumar@gmail.com>
 * @desc all operations belongs to user leads
 */
class BOMongo_UserLeadCapture extends BOMongo_Connection {

    protected $_success = true;
    protected $_collection = 'user_lead';
    protected $_collectionObj = false;

    // define class constructor
    public function __construct( $debug = true ) {
        $this->_debug = $debug;
        $mongoDatabase = self::connect();
        $this->_collectionObj = $mongoDatabase->selectCollection( $this->_collection );
    }

    /**
     * Insert bulk queries into "contact" table contact into mongo database
     * @param $bulkQueries is an arrays
     * @return true/false
     */
    public function bulkInsertCsvFileData( $bulkQueries ) {
        try {
            if ( count( $bulkQueries ) > 0 ) {
                $this->_collectionObj->batchInsert( $bulkQueries, array( 'continueOnError' => true ) );
                return true;
            }
            return false;
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    /**
     * Upsert query into "contact" table contact where bulk quries are comes from a csv file where we ready each  line from file
     * and make a bulk quries for insert and execute the quries into mongo database
     * @param $bulkQueries is an arrays
     * @return true/false
     */
    public function UpsertCsvFileData( $bulkQueries ) {
        try {
            foreach ( $bulkQueries as $i => $query ) {
                self::save( $query );
            }
            return true;
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    /**
     * Insert/Update data into table "lead capture"
     * @param $query is an array
     * @return true/false
     */
    public function save( $query ) {
        try {
            $query[ 'email' ] =  trim( strtolower( $query[ 'email' ] ) );

            $criteria = array( 'appInstanceId' => $query[ 'appInstanceId' ],
                'projectId' => $query[ 'projectId' ], "email" => $query[ 'email' ] );
            
            $token = DB_Utility::createSecretandKey( 10 );

            $updateField = array();
            $arrKeys = array_keys( $query );
            foreach ( $arrKeys as $key ) {
                if ( $key == 'lifecycleid' ) { 
                    // check if key exists then skip the update operation if already added against primary key of mongo collection
                    $updateField[ '$setOnInsert' ][ $key ] = $query[ $key ];
                } else {
                    // set the key for update
                    $updateField[ '$set' ][ $key ] = $query[ $key ];
                }
            }
            // save collection
            $result = $this->_findUpdate( $this->_collectionObj, $criteria, $updateField, array( 'upsert' => true, "w" => 1 ) );
            return true;
        } catch (Exception $ex) {
            throw $ex;
        }
    }


    /**
     * Check and get the token data if present
     * @param matchCriteria
     * @return array
     */
    public function checkAndGetUserLeadToken( $matchCriteria ) {
        try {
            $cursor = $this->_collectionObj->find( $matchCriteria );
            $cursorData = $this->_iterateCursor( $cursor );
            $result = array();
            foreach( $cursorData as $key => $data ){
                $result = $data;
            }
            return $result;
        } catch (Exception $ex) {
            $this->_log($ex->getMessage() . PHP_EOL . $ex->getTraceAsString());
        }
    }

    /**
     * @param $query is an array
     * @return true/false
     */
    public function saveLeadData( $query ) {
        try {
            // reset the email
            $query[ 'email' ] =  trim( strtolower( $query[ 'email' ] ) );
            // set the match criteria
            $criteria = array( 'appInstanceId' => $query[ 'appInstanceId' ], 
                'projectId' => $query[ 'projectId' ], "email" => $query[ 'email' ] );

            // check if records already present in the collection then get the token
            $leadData = self::checkAndGetUserLeadToken( $criteria );
            $token = count( $leadData ) > 0 ? $leadData[ 'token' ] : "";
            // check if token is empty then generate the token
            if( $token == "" ){
                $token = DB_Utility::createSecretandKey( 10 );
            }
            // set the token
            $query[ 'token' ] = $token;

            $updateField = array();
            $arrKeys = array_keys( $query );
            foreach ( $arrKeys as $key ) {
                if ( $key == 'projectId' || $key == 'appInstanceId' || $key == 'email' ) {
                    // check if key exists then skip the update operation if already added against primary key of mongo collection
                    $updateField[ '$setOnInsert' ][ $key ] = $query[ $key ];
                } else {
                    // set the key for update
                    $updateField[ '$set' ][ $key ] = $query[ $key ];
                }
            }
            // save collection
            $result = $this->_findUpdate( $this->_collectionObj, $criteria, $updateField, array( 'upsert' => true, "w" => 1 ) );

            return array( "msg" => "successfully saved", "leadCaptureToken" => $token, 'result' => $result, "responseCode" => 200 );
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    /**
     * Check and get the token data if present
     * @param matchCriteria
     * @return array
     */
    public function verifyUserLeadByToken( $matchCriteria ) {
        try {
            $message = "";
            $error = false;

            $cursor = $this->_collectionObj->find( $matchCriteria );
            $cursorData = $this->_iterateCursor( $cursor );
            if( count( $cursorData ) <= 0 ){
                $error = true;
                $message = "No data found !";
            }

            $isUpdated = false;
            $projectId = 0;
            foreach( $cursorData as $key => $data ){
                if( $data[ 'verified' ] == 'Y' ){
                    $message = "Lead already verified !";
                    $error = true;
                }else{
                    $projectId = $data[ 'projectId' ];
                    $matchCriteria = array( 'verified' => 'N', 'token' => $data[ 'token' ] );
                    
                    $updateField = array();
                    $updateField[ '$set' ][ 'verified' ] = 'Y';
                    
                    $result = $this->_findUpdate( $this->_collectionObj, $matchCriteria, $updateField );
                }
            }
            return array( 'projectId' => $projectId, 'message' => $message, 'error' => $error );
        } catch (Exception $ex) {
            $this->_log($ex->getMessage() . PHP_EOL . $ex->getTraceAsString());
        }
    }


    /**
     * Check and get the token data if present
     * @param $criteria, $limit, $skip
     * @return array
     */
    public function _find( $criteria, $limit = 10, $skip = 0 ) {
        try {
            $cursor = $this->_collectionObj->find( $criteria )->skip( $skip )->limit( $limit );
            return $this->_iterateCursor( $cursor );
        } catch ( Exception $ex ) {
            $this->_log($ex->getMessage() . PHP_EOL . $ex->getTraceAsString());
        }
    }

    /**
     * Connect to mongo db instance with selected collection( table )
     * @return collection connection object
     */
    public function connect_import_process() {
        return $this->_collectionObj;
    }

}
